package com.tools.scanner.ui.qrcode.scanner

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.mlkit.vision.barcode.common.Barcode
import com.tools.scanner.R
import com.tools.scanner.databinding.FragmentWifiScannerBinding
import com.tools.scanner.utils.connectionWifi
import com.tools.scanner.utils.copyText
import com.tools.scanner.utils.showToast

class WifiFragment : BaseScannerFragment() {

    private lateinit var mBinding: FragmentWifiScannerBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentWifiScannerBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val wifiData = getData(Barcode.WiFi::class.java) ?: return

        val entryType = when (wifiData.encryptionType) {
            Barcode.WiFi.TYPE_OPEN -> {
                "NO PASS"
            }

            Barcode.WiFi.TYPE_WPA -> {
                "WPA"
            }

            else -> {
                "WEP"
            }
        }
        mBinding.tvEntryType.text =
            resources.getString(R.string.wifi_entry_type, entryType)
        mBinding.tvWifiName.text = wifiData.ssid
        mBinding.tvWifiPwd.text = wifiData.password

        mBinding.tvCopy.setOnClickListener {
            if (wifiData.encryptionType == Barcode.WiFi.TYPE_OPEN) {
                wifiData.ssid?.let {
                    it.copyText()
                    R.string.copy_wifi_name.showToast()
                }
            } else {
                wifiData.password?.let {
                    it.copyText()
                    R.string.copy_wifi_pwd.showToast()
                }
            }
        }

        mBinding.tvConnection.setOnClickListener {
            wifiData.connectionWifi()
        }
    }

}